动态内存分配模板 class
dynamic memory allocation template class
我正在尝试为此创建一个动态内存 class 我已经创建了:
#ifndef STACK_H
#define STACK_H
#include <stdexcept>
#include "Link.h"
template <class T>
struct stack{
Link<T> * head;
stack();
void push(T * data);
T* top();
T* pop();
void cleanup();
};
#endif
源文件:
#include "stack.h"
#include <cstddef>
template <class T>
stack<T>::stack(){
head=nullptr;
}
driver:
#include "stack.h"
#include <iostream>
#include <memory>
int main(){
stack<double> oneStack();
stack<double> * oneStack2=new stack<double>;
}
当我编译代码时出现以下错误:
g++ -Wall driver.o Link.o stack.o -o driver.exe
driver.o: 在函数 main':
driver.cpp:(.text+0x1c): undefined reference to
stack::stack()'
中
由于某种原因,使用 new 关键字导致此错误?
当你写模板class时,你需要在声明它的地方定义函数,所以你应该这样写
#ifndef STACK_H
#define STACK_H
#include <stdexcept>
#include "Link.h"
template <class T>
struct stack{
Link<T> * head;
stack()
{
// Constructor code goes here
}
void push(T * data)
{
// Method code goes here
}
T* top()
{
// Method code goes here
}
T* pop()
{
// You get the idea
}
void cleanup()
{
// ...
}
};
#endif
编译器需要在同一个地方声明和定义模板 classes 和函数的原因是它实际上为每个不同的模板参数集生成一个新的 class在您的代码中使用。因此,假设您有 .h
文件,其中声明了模板 class 及其方法,并且您有一个 .cpp
文件,其中定义了这些方法。编译器尝试将 .cpp
文件编译为 .obj
文件,该文件稍后将用于 link 代码为单个可执行文件或库文件。但它不能这样做,因为它现在在这个文件中没有模板参数,所以它实际上不能为具体参数生成具体代码。像这样。
如果你想要更深入的了解,可以看这里:http://isocpp.org/wiki/faq/templates#templates-defn-vs-decl
我正在尝试为此创建一个动态内存 class 我已经创建了:
#ifndef STACK_H
#define STACK_H
#include <stdexcept>
#include "Link.h"
template <class T>
struct stack{
Link<T> * head;
stack();
void push(T * data);
T* top();
T* pop();
void cleanup();
};
#endif
源文件:
#include "stack.h"
#include <cstddef>
template <class T>
stack<T>::stack(){
head=nullptr;
}
driver:
#include "stack.h"
#include <iostream>
#include <memory>
int main(){
stack<double> oneStack();
stack<double> * oneStack2=new stack<double>;
}
当我编译代码时出现以下错误:
g++ -Wall driver.o Link.o stack.o -o driver.exe
driver.o: 在函数 main':
driver.cpp:(.text+0x1c): undefined reference to
stack::stack()'
由于某种原因,使用 new 关键字导致此错误?
当你写模板class时,你需要在声明它的地方定义函数,所以你应该这样写
#ifndef STACK_H
#define STACK_H
#include <stdexcept>
#include "Link.h"
template <class T>
struct stack{
Link<T> * head;
stack()
{
// Constructor code goes here
}
void push(T * data)
{
// Method code goes here
}
T* top()
{
// Method code goes here
}
T* pop()
{
// You get the idea
}
void cleanup()
{
// ...
}
};
#endif
编译器需要在同一个地方声明和定义模板 classes 和函数的原因是它实际上为每个不同的模板参数集生成一个新的 class在您的代码中使用。因此,假设您有 .h
文件,其中声明了模板 class 及其方法,并且您有一个 .cpp
文件,其中定义了这些方法。编译器尝试将 .cpp
文件编译为 .obj
文件,该文件稍后将用于 link 代码为单个可执行文件或库文件。但它不能这样做,因为它现在在这个文件中没有模板参数,所以它实际上不能为具体参数生成具体代码。像这样。
如果你想要更深入的了解,可以看这里:http://isocpp.org/wiki/faq/templates#templates-defn-vs-decl