2

我有一个简单的 C++ 测试类,它char * operator()运行良好。问题是,当我在堆上创建它时,我无法使用它。

test t;
printf(t);

可以,但是

test *t=new test();
printf(t);

不是。除了 printf(*t) 有什么办法吗?

4

4 回答 4

5

隐式转换char*可能听起来是个好主意,但相信我,它不是。猜猜为什么std::string没有。只需编写一个c_str方法并调用printf("%s", t->c_str()). 或者更好的是,operator<<为你的班级超载。如果您向我们展示课程,我们可以为您提供帮助。

于 2013-01-15T13:18:47.663 回答
1

Given that you really need to convert a pointer (which has to be correctly initialized, by the way...) to a char*, this isn't possible.

You can only implement operators for values (or references) of your class within the class. Some operators can be defined outside of the class, but casting operators aren't (for example, operator+ can be implemented outside, taking two parameters).

Given the fact that arithmetic operators can be implemented outside of classes (operator<< is an arithmetic operator), you can implement a stream operator for output to, for example, std::cout, even with pointers.

std::ostream & operator <<(std::ostream & o, const test & t) {
    return o << t.toString();  // use std::string here, not c-strings!
}
std::ostream & operator <<(std::ostream & o, const test * t) {
    return o << t->toString(); // use std::string here, not c-strings!
}

See live: http://ideone.com/BZfcji

于 2013-01-15T13:28:01.637 回答
0

您需要先分配内存test *t才能使用它,否则您的指针不会指向任何内存。

你这样做:

test * t= new test();

完成后,您还必须再次释放它:

delete t;

另外*t你想用什么打印printf?它指向的地址,或者它的成员的一些内容?如果是后者,您应该重载适当的运算符来执行此操作。

另一件事,不要printf在 C++ 中使用。在你的课堂上使用std::cout和超载。operator<<test

于 2013-01-15T13:17:07.803 回答
0

您可以将堆对象存储为引用,而不是指针。

test *my_heap_object = new test();
test &t = *my_heap_object;
// now you can use 't', as if it was local,
// instead of dereferencing the pointer each time.
printf(t);
t.do_something();
t++;

更多解释可以在wikipedia上找到。

于 2013-01-15T13:22:54.053 回答