【发布时间】:2018-11-01 17:43:42
【问题描述】:
我在将指针传递给由另一个指针调用的函数时遇到问题。我正在尝试修改一个调用函数 min 的指针(即 p1)(即 p1->min()),该函数将指针作为参数(即 p1->min(*p2))。注意: *p2 根本没有被修改,只是传递了它的值,p1 将根据 p2 的值进行修改。
注意:我删除了不相关的代码(仅在函数内部,其他一切按原样)以使其更易于阅读。
测试.h
// Don't worry about the create method, just assume it works
// I'm having issues with the "min" function, more details below
class Test {
protected:
std::vector<std::vector<std::string> > vec;
public:
static Test *create(std::string file); // instantiates vec
void *min(Test *); // modifies vec
};
Test.cc
// Don't worry about create (factory method), just assume it works
// "min" is causing compiler errors (see below)
Test *Test::create(string file) { /* instantiates vec with file contents */ }
void *Test::min(const Test *&p) { /* modifies vec */ }
main.cc
// Main cannot change, this is how it must be implemented
// However, Test.cc and Test.h CAN be modified.
Test *p1 = Test::create("file1");
Test *p2 = Test::create("file2");
p1->min(*p2); // modify p1 based on values of p2, p2 is NOT modified
编译器错误:
fatal error: control reaches end of non-void function
奇怪的是它声明为 void 但期望返回值 所以,当我返回一些东西时,它会显示另一个编译器错误
fatal error: no viable conversion from return value of type 'Test' to function return type 'void *'
我对编译错误感到很困惑。我认为这与我的声明有关。注意:没有构造函数,因为基类必须使用工厂方法,而派生类使用自己的构造函数,因此 *Test::create 和 *Test::min。
请帮忙。
【问题讨论】:
-
Test::min的声明与其定义不符。论据不同。你确定你想让min返回void*吗?返回值有什么意义? -
void*与void不同。投票结束为拼写错误 -
我不需要返回值。 p1->min(*p2) 只是修改了p1,不需要返回任何东西。
-
我看不到基类或派生类。如果你不打算改变返回类型,那么你必须返回一些东西。
-
tbh 我认为这个问题是火车失事。我建议你创建一个包含minimal reproducible example 的新文件(即包括你的基地)
标签: c++ pointers parameter-passing