C++ 如何编写一个函数,如果我们打印一个对象,那么它';s需要打印在对象中传递的参数
在类库中,我们需要编写一个函数,以便打印对象将使用oops概念打印对象的参数C++ 如何编写一个函数,如果我们打印一个对象,那么它';s需要打印在对象中传递的参数,c++,oop,C++,Oop,在类库中,我们需要编写一个函数,以便打印对象将使用oops概念打印对象的参数 #include <iostream> using namespace std; class base{ int num; string s; public: base(int elem,string p){ cout<<elem<<" "<<p<<endl; } // todo: }; int
#include <iostream>
using namespace std;
class base{
int num;
string s;
public:
base(int elem,string p){
cout<<elem<<" "<<p<<endl;
}
// todo:
};
int main() {
base obj(12,"shivam");
// cout<<obj<<endl;
}
#包括
使用名称空间std;
阶级基础{
int-num;
字符串s;
公众:
基本(整数元素,字符串p){
cout您当前的想法离工作不远,除非您在创建base
实例后立即将构造函数参数打印到std::cout
,而不是在使用该类的程序员表达这样的愿望时。您需要做的是保存在构建base
时给出的参数。然后您就可以按需打印
例如:
#include <iostream>
#include <string>
class base {
public:
base(int n, const std::string& str) : // save the arguments given using
num(n), s(str) // <- the member initializer list
{
// empty constructor body
}
// declare a friend function with special privileges to read private
// member variables and call private functions:
friend std::ostream& operator<<(std::ostream&, const base&);
private:
int num;
std::string s;
};
// define the free (friend) function with access to private base members:
std::ostream& operator<<(std::ostream& os, const base& b) {
// here you format the output as you'd like:
return os << '{' << b.num << ',' << b.s << '}';
}
int main() {
base obj(12,"shivam");
std::cout << obj << '\n';
}
试试这个:
int IntS(int y)
{
return y;
}
class base{
public:
base(int enume, std::string str)
{
std::cout << IntS(enume) << '\n';
std::cout << str << '\n;
}
};
int main()
{
base mybase(IntS(5), "five");
return 0;
}
intints(inty)
{
返回y;
}
阶级基础{
公众:
基(int枚举,std::string str)
{
std::看一看问题,它解决了打印问题。对于传递给obj
的参数,看一看构造函数。如果搜索“c++重载输出”你可以找到大量的教程。你能解释为什么你使用引用来返回吗?@ SHIVAMJAIN引用和C++一样轻量级。引用甚至不需要占用真实内存。在<代码> oStase<代码>上面,这是另一个重要的原因。示例<代码>
int IntS(int y)
{
return y;
}
class base{
public:
base(int enume, std::string str)
{
std::cout << IntS(enume) << '\n';
std::cout << str << '\n;
}
};
int main()
{
base mybase(IntS(5), "five");
return 0;
}