简体   繁体   English

C ++重载带有参数的朋友类函数参数

[英]C++ overloading a friend class function parameter with an argument

I'm not sure if the term overloading applies here, but what I would like to do, is inherit a class and then call it's member function without any parameters, so that the parameter is automatically inherited from the current class member variable. 我不确定重载一词在这里是否适用,但是我想做的是继承一个类,然后在没有任何参数的情况下调用它的成员函数,以便该参数自动从当前类的成员变量继承。 It's easier to explain in code, so I'll post it down here: 用代码解释起来更容易,所以我将其发布在这里:

#include <iostream>

template <typename T>
struct Singleton {
    static T & Instance() {
        static T instance;
        return instance;
    }

    T * operator -> () const {
        return &Instance();
    }
};

struct SFoo : Singleton<SFoo> {
    void Print( int a = 0 ) {
        printf( "%d\n", a );
    }
};

struct SBar : SFoo {
    const static int b = 42;
    friend void Print( int a = b); // <- Should call SFoo::Print() with integer b as the argument
};

int main() {
    using Foo = Singleton<SFoo>;
    using Bar = Singleton<SBar>;

    Foo()->Print( 123 ); // Should print: 123
    Bar()->Print();      // Should print: 42

    getchar();
    return 0;
}

I've relatively new to inheritance and can't seem to figure such a simple piece of code out. 我对继承还比较陌生,似乎无法弄清楚这么简单的代码。 The result right now yields in printing 123 and 0 (default argument of SFoo::Print() ), which is not expected. 现在,结果将在打印1230SFoo::Print()默认参数)中产生,这是不期望的。

void Print(int a = b) { SFoo::Print(a); }

makes it work, as you've pointed out, it can also be: 正如您所指出的,它也可以工作:

void Print() { SFoo::Print(b); }

because we don't need two versions that accept an int . 因为我们不需要两个接受int版本。

On the other hand, you were declaring a friend (which is a non-member function). 另一方面,您正在声明一个friend (这是一个非成员函数)。 It wasn't called anywhere in the program ( Bar()->Print(); calls SFoo::Print ), and you didn't get a linker error because of the missing definition. 在程序的任何地方都没有调用它( Bar()->Print();调用SFoo::Print ),并且由于缺少定义,您没有收到链接器错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM