0

有没有办法让#define 与自定义对象一起工作?
这是一个例子来说明我的意思:

#include <iostream>
#define i Complex z; z.Re=0; z.Im=1 //<-error
using namespace std;

class Complex{
    public:
        double Re;
        double Im;
        void operator=(Complex z){
            this->Im=z.Im;this->Im=z.Re;
        }
};

int main(){
    Complex a = i; //<- the "i" (line 15)
    cout<< a.Re<< endl<< a.Im;
    return 0;
}

在此代码中,它在第 2 行显示错误:“expected primary-expression before 'a'”。
我希望将第 15 行中的“i”替换为具有正确属性的对象。
如果用#define 做类似的工作是不可能的,你能用完全不同的方法来做吗?

4

1 回答 1

3

解决这个问题的一种方法是添加一个构造函数,然后创建一个const你可以根据需要引用的:

#include <iostream>

class Complex {
public:
    double Re;
    double Im;

    // Add a simple constructor
    Complex(const double r, const double i) : Re(r), Im(i) { };

    Complex& operator=(Complex z) {
        // Don't jam things up on the same line
        this->Im = z.Im;
        this->Im = z.Re;

        return *this;
    }
};

// Define a constant. Note not `i` which is a very common iterator variable.
const Complex I = { 0, 1 };

int main() {
    Complex a = I; // Assignment is fine

    std::cout << a.Re << std::endl << a.Im;

    return 0;
}

另一种方法是Complex::I定义一个static属性以避免污染全局命名空间。

在 C++#define中很少是最好的选择。这通常是最糟糕的。#define在各种非平凡的用例下表现良好可能极具挑战性,这就是为什么它们最好保留在所有其他选项都已用尽的特殊情况下。

于 2021-03-03T13:54:17.477 回答