# 如何在假定类中传递变量？

``````#include <math.h>
#include <iostream>
#include <typeinfo>
#include <string>

class quat
{
public:
quat()
{

}
quat(double r, double i, double j, double k)
{
r_ = r;
i_ = i;
j_ = j;
k_ = k;
}
friend std::ostream& operator<<(std::ostream& os, const quat& q)
{
os << q.r_ << ", " << q.i_ << ", " << q.j_ << ", " << q.k_;
return os;
}
quat Inv()
{
quat q;
double L = sqrt(this->r_*this->r_ + this->i_*this->i_ + this->j_*this->j_ + this->k_*this->k_);
q.r_ = this->r_/L;
q.i_ = -1*this->i_/L;
q.j_ = -1*this->j_/L;
q.k_ = -1*this->k_/L;
}
private:
double r_;
double i_;
double j_;
double k_;
};

class myClass
{
public:
myClass(const int& p1, const std::string& p2, const quat& p3)
{

std::cout << "param1: " << param1_ << std::endl;
std::cout << "param2: " << param2_ << std::endl;
std::cout << "param3: " << param3_ << std::endl;
}
private:
template<typename T, typename S>void loadParam(T& in, S& param)
{
if(typeid(param) == typeid(int))
{
std::cout << "Load integer" << std::endl;
param = in;
}
else if(typeid(param) == typeid(std::string))
{
std::cout << "Load string" << std::endl;
param = in;
}
else if(typeid(param) == typeid(quat))
{
std::cout << "Load quat" << std::endl;
param = in.Inv();
}
}
int param1_;
std::string param2_;
quat param3_;
};

int main() {
quat q;
myClass a(1, "test", q);

return 0;
}
``````

``````/home/yuan/Code/test/src/common.cpp: In instantiation of ‘void myClass::loadParam(T&, S&) [with T = const int; S = int]’:
/home/yuan/Code/test/src/common.cpp:48:25:   required from here
/home/yuan/Code/test/src/common.cpp:72:11: error: request for member ‘Inv’ in ‘in’, which is of non-class type ‘const int’
param = in.Inv();
^
/home/yuan/Code/test/src/common.cpp: In instantiation of ‘void myClass::loadParam(T&, S&) [with T = const std::__cxx11::basic_string<char>; S = std::__cxx11::basic_string<char>]’:
/home/yuan/Code/test/src/common.cpp:49:25:   required from here
/home/yuan/Code/test/src/common.cpp:72:11: error: ‘const class std::__cxx11::basic_string<char>’ has no member named ‘Inv’
/home/yuan/Code/test/src/common.cpp: In instantiation of ‘void myClass::loadParam(T&, S&) [with T = const quat; S = quat]’:
/home/yuan/Code/test/src/common.cpp:50:25:   required from here
/home/yuan/Code/test/src/common.cpp:72:11: error: passing ‘const quat’ as ‘this’ argument discards qualifiers [-fpermissive]
/home/yuan/Code/test/src/common.cpp:25:7: note:   in call to ‘quat quat::Inv()’
quat Inv()
``````