假设我在两个不同的命名空间中定义了方法:
namespace foo
{
void print()
{
//do work...
}
}
namespace bar
{
void print()
{
//do work...
}
}
Run Code Online (Sandbox Code Playgroud)
该foo::print()和bar::print()功能是完全平等的.我的项目使用了这些函数的大量调用.
有没有办法删除其中一个print()定义而不更改这些函数的调用?我的意思是类似下面的东西(当然,C++语言不允许这种结构,它只是一个例子):
namespace foo, bar //wrong code!
{
void print()
{
//do work...
}
}
Run Code Online (Sandbox Code Playgroud)
如果没有办法按我的意愿重构代码,请告诉我,你喜欢以下决定吗?如果您的项目包含此类代码,您会感到高兴吗?:)
namespace foo
{
void print()
{
//do work...
}
}
namespace bar
{
void print()
{
foo::print();
}
}
Run Code Online (Sandbox Code Playgroud)
加:
谢谢你们,我对你的答案非常满意.我想让你澄清一下:using ::foo::print和之间有区别using foo::print吗?
我的意思是以下问题.然后我尝试const使用typeinfo库知道指针的类型和常量,我们得到它们:
int* pY1 = 0;
const int* pY2 = 0;
std::cout << "pY1: " << typeid(pY1).name() << std::endl;
std::cout << "pY2: " << typeid(pY2).name() << std::endl;
Run Code Online (Sandbox Code Playgroud)
输出:
pY1: int *
pY2: int const *
Run Code Online (Sandbox Code Playgroud)
但后来我尝试以下方法
int x1 = 0;
const int x2 = 0;
std::cout << " x1: " << typeid(x1).name() << std::endl;
std::cout << " x2: " << typeid(x2).name() << std::endl;
Run Code Online (Sandbox Code Playgroud)
输出是
x1: int
x2: int
Run Code Online (Sandbox Code Playgroud)
ideone代码
是否可以识别运行时中的常量?如果是的话,怎么做?
运营商在这里超载了什么?
operator T * ()
我知道operator方法具有以下结构:
type operator operator-symbol ( parameter-list )
假设我们有以下代码
template<typename T> class SmartPtr
{
public:
SmartPtr(T* data): member(data) {}
T* member;
T& operator * () { return *member; } //usage: *TObj
T*& operator () () { return member; } //usage: TObj()
operator T * () { return member; } //usage: ???
};
Run Code Online (Sandbox Code Playgroud)
如果您在ideone上尝试它,则没有编译错误.那么这里发生了什么?
假设我有一个具有不同构造函数的类:
class A
{
public:
A(char* string)
{
//...
}
A(int value)
{
//..
}
void check() {}
};
Run Code Online (Sandbox Code Playgroud)
现在我想在堆栈上创建一个A对象,必须根据某些条件选择构造函数,但是存在一个问题:创建的对象被销毁然后我们退出{...}块.
bool isTrue() { /*...*/ }
int main()
{
if (isTrue())
{
A a("string");
}
else
{
A a(10);
}
a.check(); //error: 'a' is not defined in this scope
}
Run Code Online (Sandbox Code Playgroud)
假设我有没有拷贝构造函数或operator=在A类.那怎么能解决这个问题呢?
http://ideone.com/YsjmnK