我正在学习C++,并了解到int类型只是预制类。所以我想也许我应该尝试创建一个。
我基本上想做的是一个普通类 int
int x;
x=7;
cout << x;
屏幕上的输出为 7。
所以类似...
abc x;
x=7;
cout << x;
我会放什么
class abc{
\ HERE!!!!!!
};
所以我可以这样做
class SomeClass {
public:
int x;
SomeClass(int x) {
this->x = x;
}
};
int main(int argc, char *argv[]) {
SomeClass s = 5;
cout << s.x << "n"; // 5
s = 17;
cout << s.x << "n"; // 17
return 0;
}
但正如你所看到的,我必须使用 s.x 来打印值 - 我只想使用"s"。我把它作为一个实验来做,我不想听到这种方法是好是坏,毫无意义还是革命性,或者不能做到。我记得有一次我做过。但只能通过复制和粘贴我不完全理解甚至忘记的代码。
并了解到 int、类型只是预制类
这是完全错误的。不过,您可以完全控制类在表达式中的行为方式,因为您可以重载(几乎)任何运算符。您在这里缺少的是当您这样做时调用的通常operator<<
重载:
cout<<s;
您可以像这样创建它:
std::ostream & operator<<(std::ostream & os, const SomeClass & Right)
{
Os<<Right.x;
return Os;
}
有关详细信息,请参阅有关运算符重载的常见问题解答。
<<和>>基本上是函数名称。 您需要为您的类定义它们。 与 +、-、* 和所有其他运算符相同。 方法如下:
http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html
你需要为你的类重载operator<<
,如下所示:
class abc
{
public:
abc(int x) : m_X(x) {}
private:
int m_X;
friend std::ostream& operator<<(std::ostream& stream, const abc& obj);
};
std::ostream& operator<<(std::ostream& os, const abc& obj)
{
return os << obj.m_X;
}
您不必friend
operator<<
过载,除非您想要访问受保护/私有成员。
在类中定义abc
将运算符转换为 int 和从 int 赋值运算符,就像在以下模板类中一样:
template <class T>
class TypeWrapper {
public:
TypeWrapper(const T& value) : value(value) {}
TypeWrapper() {}
operator T() const { return value; }
TypeWrapper& operator (const T& value) { this->value = value; return *this; }
private:
T value;
};
int main() {
TypeWrapper<int> x;
x = 7;
cout << x << endl;
}
您希望重载输出运算符:
std::ostream& operator<< (std::ostream& out, SomeClass const& value) {
// format value appropriately
return out;
}