【发布时间】:2017-07-04 03:11:55
【问题描述】:
我在这里遇到了一个有趣的困境,如果我通过值将变量传递给函数,但如果我通过引用传递它,代码将编译,我不知道为什么。在 header.h 中:
#include <iostream>
#include <string>
void get_name(std::string &name)
{
getline(std::cin, name);
return;
}
template <class T, class U>
class readonly
{
friend U;
private:
T data;
T& operator=(const T& arg) {data = arg; return data;}
public:
operator const T&() const {return data;}
};
class myClass
{
private:
typedef readonly<std::string, myClass> RO_string;
public:
RO_string y;
void f()
{
get_name(y); // compile error
}
};
main.cpp 实现文件只包含这个头文件,创建myClass 的实例,然后调用f()。这样做时,它将无法正确编译。问题在于我通过引用get_name 函数来传递变量y。如果我更改函数以便我通过值传递,那么一切都会正确编译并按预期工作(除非我显然不再对y 进行更改)。但是,我不理解这种行为。 为什么会发生这种情况?在这种情况下是否有解决此问题的最佳方法?
【问题讨论】:
-
一个
readonly类?有趣的。这是不必要的,但同时也是不言自明的。
标签: c++ class templates readonly