C ++:私有方法返回的本地typedef

时间:2015-06-26 09:01:04

标签: c++ return-value typedef private

下面的代码不正确,我理解为什么,get_point返回类型在类外未知的值:

class C {
    typedef std::pair<double, double> Point;
 public:
    Point get_point() const;
};

Point C::get_point() const {
    [...]
}

但为什么下面的代码不正确呢?本地类型不在课堂外使用!

class C {
    typedef std::pair<double, double> Point;
 private:
    Point get_point() const;
};

Point C::get_point() const {
    [...]
}

当我们使用C::时,我们应该在课堂内,所以我们应该可以使用Point

3 个答案:

答案 0 :(得分:5)

这是一个有效的代码。这是一个示范程序

#include <iostream>
#include <utility>

class C 
{
    typedef std::pair<double, double> Point;
    Point p { 10.10, 20.20 };
 public:
    Point get_point() const;
};

C::Point C::get_point() const { return p; }

int main() 
{
    C c;

    auto p = c.get_point();

    std::cout << p.first << ' ' << p.second << std::endl;

    std::pair<double, double> p2 = c.get_point();

    std::cout << p2.first << ' ' << p2.second << std::endl;
}

程序输出

10.1 20.2
10.1 20.2

您不仅可以使用名为C::Point的名称std::pair<double, double>

至于此代码

class C {
    typedef std::pair<double, double> Point;
 private:
    Point get_point() const;
};

Point C::get_point() const {
    [...]
}

然后你必须写

C::Point C::get_point() const {

在定义类的范围内搜索用作类定义外定义的类成员函数的返回类型的非限定名称。而且没有名字Point。您必须使用合格的名称。

答案 1 :(得分:2)

函数C::get_point()的定义在全局范围内,Point不是,因此您必须指定Point所在的位置。如果将定义移动到类中,则在使用C::时不必指定typedef(Point)的范围:

class C {
    typedef std::pair<double, double> Point;
public:
    Point get_point() const {
        return Point( 1.0, 2.0 );
    }
};

答案 2 :(得分:2)

As a brief answer to the question (detailed in the other answers), in the definition of;

Point C::get_point() const {
  //...
} 

Needs to be;

C::Point C::get_point() const {
  //...
} 

Such that the Point in the scope of C is found.

It is worth noting, that if the typedef is private, the name of the type (being Point) can't be used outside of the class. Client code will either need to use auto (or otherwise specify the type).

As per the following sample;

class C {
    typedef std::pair<double, double> Point;
public:
    Point get_point() const;
};

C::Point C::get_point() const {
    return Point(); // dummy code to compile sample
}

int main()
{
    C c;
    //C::Point a = c.get_point(); // fails to compile (would compile if Point typedef was public
    auto a = c.get_point(); // compiles
}