C++自定义类重载运算符出现的一堆问题

今天我在自定义类重载运算符<<时遇到了一个很奇怪的报错......

先上最后能够正常运行的代码吧(相关头文件在stdafx.h里面,懒得打了)

// point.h

class point
{
public:
	point(int x, int y);

	string printPos(); // "[3,5]"
	friend ostream &operator<<(ostream &os, const point &p); // [3,5]

private:
	int X, Y;
};

// point.cpp

#include "stdafx.h"
#include "point.h"

point::point(int x, int y)
{
	X = x;
	Y = y;
}

string point::printPos() // "[3,5]"
{
	return "[" + to_string(X) + "," + to_string(Y) + "]";
}


ostream &operator<<(ostream &os, const point &p) // [3,5]
{
	os << "[" + to_string(p.X) + "," + to_string(p.Y) + "]" << endl;
	return os;
}

// ConsoleApplication2.cpp

#include "stdafx.h"
#include "point.h"

int main()
{
	point p(3, 5);
	cout << p;
    return 0;
}

是一个很简单的重载<<运算符的函数,但是我是看博客照猫画虎搞下来的。

friend,&,const这些大概有什么用我理解,但是具体为什么这么写我不是很清楚。所以不理解后续的各种问题。

 

(1)删掉const就报错。

error C2248: “point::X”: 无法访问 private 成员(在“point”类中声明)

error C2248: “point::Y”: 无法访问 private 成员(在“point”类中声明)

喵喵喵?上面的to_string(X) 可以直接访问X,这里就不可以了?就算不可以,为啥加了一个const就可以了?

看着p.觉得有点多余,删掉看看。

 

(2)删掉p.加不加const都报错

error C2065: “X”: 未声明的标识符

error C2065: “Y”: 未声明的标识符

果然还是报错,但是还是不明白为什么不可以直接访问。

 

话说我干嘛一定要删掉const?因为我最最开始打算这样写的......

ostream &operator<<(ostream &os, const point &p) // [3,5]
{
	os << p.printPos() << endl;
	return os;
}

报错:error C2662: “std::string point::printPos(void)”: 不能将“this”指针从“const point”转换为“point &”

(诶?这个const不一样有什么关系么?)

好吧,有关系就有关系吧,那我删掉上面代码的const看看?那不是就类型一样的吗?

于是......

一脸懵逼......这是什么错误???MSDN的解释我大概看得懂,但是不明白和我有啥关系,摔!

https://docs.microsoft.com/zh-cn/cpp/error-messages/tool-errors/linker-tools-error-lnk2019?f1url=https%3A%2F%2Fmsdn.microsoft.com%2Fquery%2Fdev15.query%3FappId%3DDev15IDEF1%26l%3DZH-CN%26k%3Dk(LNK2019)%26rd%3Dtrue

 

当然,改写成最开头的形式(不要尝试在里面调用p)就不会有这么多问题了。但是这到底是什么问题啊,好烦。

还有一个神奇的事情......如果我把函数直接写在point.h的文件里时,直接删掉const就可以正常运行了。

class point
{
public:
	point(int x, int y);

	string printPos(); // "[3,5]"
	friend ostream &operator<<(ostream &os, const point &p); // [3,5]

private:
	int X, Y;
};

point::point(int x, int y)
{
	X = x;
	Y = y;
}

string point::printPos() // "[3,5]"
{
	return "[" + to_string(X) + "," + to_string(Y) + "]";
}


ostream &operator<<(ostream &os, point &p) // [3,5]
{
	os << p.printPos() << endl;
	return os;
}

喵喵喵???为什么???

(不出意外的,下面这种写法也是可以的......当然把整个point.h里面的函数都复制到main函数的文件里也是可以的)

class point
{
public:
	point(int x, int y)
	{
		X = x;
		Y = y;
	}

	string printPos() // "[3,5]"
	{
		return "[" + to_string(X) + "," + to_string(Y) + "]";
	}

	friend ostream &operator<<(ostream &os, point &p) // [3,5]
	{
		os << p.printPos() << endl;
		return os;
	}

private:
	int X, Y;
};

所以到底是为什么嘛......orz

 

————————————————————————

刚刚发文的时候不知道为什么,只要在标题栏输入<<就发不了,果然是一堆问题

————————————————————————

妈耶,突然想起来!

我在删point.cpp里面函数的const的时候忘记把point.h里面的const一起删掉了......

难怪无法解析......一起都删掉就没什么毛病了。(虽然按道理来说最好别删...)

我大概就是这么傻......

可是为什么......

上面我把函数直接写在point.h的文件里时,直接删掉const就可以正常运行了。

喵喵喵???

 

 

你可能感兴趣的:(C++)