开发者

c++ linux access an object from a method

HI,

H开发者_高级运维ow can I define an object in a method?

std::string method(std::string name, &pointer_to_any_class)
{
//code
}?

if I have a Class like Class *x= new Class(); Can i have method like Method("me",*x);?

Class_me *y= new Class_me(); 
method("hey",*y);//will this mean that &pointer_to_any_class is a pointer to Class_me?


If Class_me is derived from Class then it will work:

class Class
{
    ...
}

class Class_me : public Class
{
    ...
}

std::string method(const std::string &name, Class *cls)
{
    ...
}

Class *x = new Class();
Class_me *y = new Class_me();

method("me", x);
method("hey", y);


A function template can accept a variety of types that need not be related to each other:

template<typename T>
std::string
method(std::string const& name, T& t)
{
    // here t is a reference to type T
    return "";
}

Class x;
Class_me y;
method("me", x) // calls method<Class>
method("hey", y) // calls method<Class_me>

I couldn't have the template do anything useful because your question is too vague (also your method is not a method).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜