修复 C++ 中的"this"错误
Fixing "this" error in c++
我还是c++的新手,我想知道为什么我的cpp文件中的每个"this"实例都会出现错误"在非成员函数中无效使用"this"。
cpp文件(just方法(
ostream & operator<< (ostream & outS, Complex & rhs) {
cout << this->real;
if (this->imag < 0) {
cout << "-";
if (this->imag != -1)
cout << (-this->imag);
cout << "i";
} else if (this->imag >0){
cout << "+";
if (this->imag != 1)
cout << this->imag;
cout << "i";
return outS;
}
头文件(的一部分(
public:
friend ostream & operator<< (ostream&, Complex&);
我似乎也收到了错误"Complex"没有命名类型Complex::Complex(const Complex&object("^
cpp文件
Complx::Complex (const Complex& object) {
real = object.real;
imag = object.imag;
}
头文件
public:
Complex (const Complex&);
任何帮助都将不胜感激,如果需要,我可以发布我的代码的其余部分(我认为只发布部分代码会更容易阅读(。
this
指的是当前对象——该方法所属的对象。当您的方法单独存在时,它不是对象的一部分,因此this
没有任何意义。似乎您要指的不是this->
,而是rhs.
。
在operator<<
中,它不是类的成员。因此,它没有this
指针,该指针仅用于类非静态成员。
class Complex
{
double imag, real;
public:
Complex(const _real=0.0, const _imag=0.0);
Complex(const Complex&);
// friend functions are not member of the class
friend ostream& operator<< (ostream&, Complex&);
// this is a member of the class
Complex operator+(Complex& another)
{
// I am a member so I have 'this' pointer
Complex result;
result.real = this->real + another.real;
result.imag = this->imag + another.imag;
return result;
}
};
ostream& operator<<(ostream& stream, Complex& rhs)
{
// I do not have 'this' pointer, because I am not a member of a class
// I have to access the values via the object, i.e. rhs
stream << rhs.real << "+" << rhs.imag << 'i';
return stream;
}
然而,我的问题是,你为什么要使用"friend operator<lt;'?IMHO它不应该是类的朋友,相反,类应该提供类似double image() const { return this->imag; }
的函数,非朋友operator<<
可以通过这些函数访问值。
相关文章:
- C++错误:"error: int aaa::bbb is protected within this context"
- 类中的数组变量C++导致"was not declared in this scope"实现文件的一个函数中错误,但在构造函数中不会导致错误
- 错误:类没有名为"ThisW"的成员;你是说"这个"吗?但是代码没有说"ThisW",它已经说了"This"
- C++ 中的构造函数、继承、堆栈、堆、this-pointer 和段错误
- C++ Boost - 序列化错误 - 将"const B"作为"this"参数
- 整体模板参数。错误:在常量表达式中使用'this'
- 如何解决"cout was not declared in this scope"错误?
- 从 std::ostream 重载 << 运算符时,为什么编译器会给出"too many parameters for this operator function"错误?
- 即使包含 <time.h 后仍"‘CLOCK_PER_SEC’ was not declared in this scope"错误>
- 使用 boost::序列化代码将 *this 传递给模板函数会产生错误
- С 错误"s1, s2 are used uninitialised in this function"
- 有没有办法绕过错误"因为'this'参数会丢弃限定符?
- 为什么直接传递"this"指针来存档是一个错误,而另一个相同类型的指针是可以的?
- "this" Lambda 捕获的是不正确的。海湾合作委员会编译器错误?
- C++ 中的"this declaration has no storage class or type specifier"错误
- Windows 10 环境中的"This version of XAudio2 is available only in Windows 8"错误
- C++错误:将"const umap_int {aka const std::unordered_map<int, int>}"作为"this"参数会丢弃限定符 [-permissive]
- 错误:将 x 作为 x 的参数传递'this'丢弃限定符
- 尝试使用指针时出现预期表达式"this"错误
- 修复 C++ 中的"this"错误