在自定义向量类中重载和运算符 作为一个练习,在C++中学习动态内存分配,我正在自己编写向量类。我在重载求和运算符时遇到了一点困难,所以我想我应该转到这里来了解一下为什么这不起作用。以下是我目前掌握的情况: template<typename T> class vector { private: T* pointer_; unsigned long size_; public: // Constructors and destructors. vector(); template<typename A> vector(const A&); template<typename A> vector(const A&, const T&); vector(const vector<T>&); ~vector(); // Methods. unsigned long size(); T* begin(); T* end(); vector<T>& push_back(const T&); // Operators. T operator[](unsigned long); vector<T>& operator=(const vector<T>&); friend vector<T>& operator+(const vector<T>&, const vector<T>&); };

在自定义向量类中重载和运算符 作为一个练习,在C++中学习动态内存分配,我正在自己编写向量类。我在重载求和运算符时遇到了一点困难,所以我想我应该转到这里来了解一下为什么这不起作用。以下是我目前掌握的情况: template<typename T> class vector { private: T* pointer_; unsigned long size_; public: // Constructors and destructors. vector(); template<typename A> vector(const A&); template<typename A> vector(const A&, const T&); vector(const vector<T>&); ~vector(); // Methods. unsigned long size(); T* begin(); T* end(); vector<T>& push_back(const T&); // Operators. T operator[](unsigned long); vector<T>& operator=(const vector<T>&); friend vector<T>& operator+(const vector<T>&, const vector<T>&); };,c++,C++,我的编译器(VS2013)在尝试编译此代码时返回一个未解析的外部符号错误,这(据我所知)意味着我不确定问题出在哪里,但是:模板向量(const A&)构造函数工作正常。我错过了什么 您没有正确地为模板运算符函数建立友好关系。有多种方法可以做到这一点,每种方法都有优点。一个是世界之友意识形态,模板的所有扩展都是彼此的朋友。我宁愿限制得更严格一点 在vector类上方,执行以下操作: template<typename T> class vector; template<type

我的编译器(VS2013)在尝试编译此代码时返回一个
未解析的外部符号
错误,这(据我所知)意味着我不确定问题出在哪里,但是:
模板向量(const A&)
构造函数工作正常。我错过了什么

您没有正确地为模板运算符函数建立友好关系。有多种方法可以做到这一点,每种方法都有优点。一个是世界之友意识形态,模板的所有扩展都是彼此的朋友。我宁愿限制得更严格一点

在vector类上方,执行以下操作:

template<typename T>
class vector;

template<typename T>
vector<T> operator+(const vector<T>& lhs, const vector<T>& rhs);
模板
类向量;
模板
向量运算符+(常量向量和lhs、常量向量和rhs);
操作将继续进行,但请注意友元声明中的语法:

// vector class goes here....
template<typename T> class vector
{
    .... stuff ....

   friend vector<T> operator+<>(const vector<T>&, const vector<T>&);
};
//向量类在这里。。。。
模板类向量
{
东西
友元向量运算符+(常数向量&,常数向量&);
};
然后定义剩下的部分。这会让你达到我认为你想要达到的目标

祝你好运


PS:上述代码中固定的引用返回值无效。

所有代码都是,对吗?还要注意,您返回的是局部变量“result”的引用。您声明了一个非模板
friend
函数,但从未定义过一个函数(稍后您定义了模板
friend
)。有关详细信息,请参见第页。请注意,gcc将使用
-Wall
标志警告上述情况,不确定VS是否也这样做。请尝试替换
友元向量和运算符+(常量向量和常量向量和)使用
模板友元向量和运算符+(常量向量和,常量向量和)在实现中的
运算符+
前面添加
向量::
,谢谢--这似乎解决了求和运算符的问题。澄清一下:通过值返回
向量的函数意味着,无论我将总和分配给什么(即
a=b+c
),它的私有成员(
指针
大小
)都将被分配
结果
持有的值,对吗?在完成任务时遇到一些困难(但这可能是稍后要问的另一个问题…)
template<typename T>
class vector;

template<typename T>
vector<T> operator+(const vector<T>& lhs, const vector<T>& rhs);
// vector class goes here....
template<typename T> class vector
{
    .... stuff ....

   friend vector<T> operator+<>(const vector<T>&, const vector<T>&);
};