c++ - 为 vector<double> 类重载 *, +, -' 运算符

标签 c++ class operator-overloading stdvector

我正在编写一个 Line 类来制作数值方法,我想要这些运算符 (*、+、-) 使我的代码更具可读性和更容易理解。

        #include <vector>

        using namespace std;

        typedef vector<double> Vector;

        class Line : public Vector
        {
        public:
            Line();
            ~Line();

            Line operator+(Line);
            Line operator-(Line);
            Line operator*(double);
        };


        Line Line::operator*(double alfa)
        {
            Line temp;
            int n = size();
            temp.resize(n);
            for (int i = 0; i < n; i++)
            {
                temp.at(i) = this->at(i)*alfa;
            }
            return temp;
        }

        Line Line::operator+(Line line)
        {
            int n = size();
            Line temp;
            temp.resize(n);
            for (int i = 0; i < n; i++)
            {
                temp.at(i) = this->at(i) + line[i];
            }
            return temp;
        }

        Line Line::operator-(Line line)
        {
            int n = size();
            Line temp;
            temp.resize(n);
            for (int i = 0; i < n; i++)
            {
                temp.at(i) = this->at(i) - line[i];
            }
            return temp;
        }


        int main()
        {
            return 0;
        }

是否可以从 Vector 类中重载此类运算符?我应该只创建函数(或方法)而不是运算符吗?还有其他建议吗?

ps1:我使用 Visual Studio 11 作为编译器。

ps2:我还没有将项目作为“win32 项目”启动,它是控制台应用程序。

我收到以下错误:

Error   1   error LNK2019: unresolved external symbol "public: __thiscall Line::Line(void)" (??0Line@@QAE@XZ) referenced in function "public: class Line __thiscall Line::operator*(double)" (??DLine@@QAE?AV0@N@Z) C:\Users\Lucas\Documents\Visual Studio 11\Projects\test\test\test.obj   test


Error   2   error LNK2019: unresolved external symbol "public: __thiscall Line::~Line(void)" (??1Line@@QAE@XZ) referenced in function "public: class Line __thiscall Line::operator*(double)" (??DLine@@QAE?AV0@N@Z)    C:\Users\Lucas\Documents\Visual Studio 11\Projects\test\test\test.obj   test

最佳答案

您必须在全局范围内重载运算符:

vector<double> operator*(const vector<double>& v, double alfa)
{
    ...
}

vector<double> operator+(const vector<double>& v1, const vector<double>& v2)
{
    ...
}

vector<double> operator-(const vector<double>& v1, const vector<double>& v2)
{
    ...
}

至于链接器错误,看起来您没有实现 Line 构造函数和析构函数。

关于c++ - 为 vector<double> 类重载 *, +, -' 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14420209/

相关文章:

c++ - 我怎样才能防止这些内存泄漏?

java - 从同一包中的不同类调用新方法

c++ - 为什么重载 operator->() 有用?

c++ - 如何在 C++ 中使用 << 将 unsigned/signed char 或 <cstdint> 类型输出为整数

c++ - 为旧的 Linux 环境编译 C++ 应用程序

c++ - shared_ptr 尚未拥有的实例的 shared_from_this() 总是返回 null?

java - Android类设计

java - 从 JAR 文件导入安全类

c++ - 我如何着手重载 C++ 运算符以允许链接?

c++ - 新分配的先前数据会发生什么变化?